<!-- src/components/MothGame.vue -->
<template>
    <div class="moth-game-container">
        <div class="game-header">
            <h1>作弊飞蛾</h1>
            <div class="score-container">
                <span class="score-label">得分:</span>
                <span class="score">{{ score }}</span>
            </div>
            <div class="time-container">
                <span class="time-label">时间:</span>
                <span class="time">{{ timeLeft }}s</span>
            </div>
        </div>

        <div class="game-area" @click="handleBackgroundClick">
            <!-- 飞蛾元素 -->
            <div v-for="moth in moths" :key="moth.id" class="moth" :class="{
                'moth-large': moth.size === 'large',
                'moth-medium': moth.size === 'medium',
                'moth-small': moth.size === 'small',
                'moth-cheat': moth.isCheat,
                'moth-clicked': moth.clicked
            }" :style="{
                left: `${moth.x}px`,
                top: `${moth.y}px`,
                transform: `scale(${moth.scale})`
            }" @click.stop="handleMothClick(moth)">
                <div class="moth-wing left"></div>
                <div class="moth-wing right"></div>
                <div class="moth-body"></div>
                <div class="moth-eye left"></div>
                <div class="moth-eye right"></div>
            </div>

            <!-- 特殊效果 -->
            <div v-for="effect in effects" :key="effect.id" class="effect" :class="effect.type" :style="{
                left: `${effect.x}px`,
                top: `${effect.y}px`
            }">
                {{ effect.value > 0 ? '+' + effect.value : effect.value }}
            </div>
        </div>

        <div class="game-controls">
            <button v-if="gameState === 'idle'" class="start-button" @click="startGame">
                开始游戏
            </button>

            <button v-if="gameState === 'playing'" class="cheat-button" @click="useCheat">
                使用作弊 ({{ cheatCount }}次)
            </button>

            <button v-if="gameState !== 'idle'" class="reset-button" @click="resetGame">
                重置游戏
            </button>
        </div>

        <div v-if="gameState === 'gameOver'" class="game-over-overlay">
            <div class="game-over-content">
                <h2>游戏结束!</h2>
                <p>最终得分: {{ score }}</p>
                <button class="restart-button" @click="startGame">再玩一次</button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted, computed } from 'vue'

// 定义类型
interface MOTH {
    id: number
    x: number
    y: number
    size: 'small' | 'medium' | 'large'
    scale: number
    isCheat: boolean
    clicked: boolean
}

interface EFFECT {
    id: number
    x: number
    y: number
    value: number
    type: 'positive' | 'negative' | 'cheat'
    createdAt: number
}

export default defineComponent({
    name: 'MothGame',
    setup() {
        // 游戏状态
        const gameState = ref<'idle' | 'playing' | 'gameOver'>('idle')
        const score = ref(0)
        const timeLeft = ref(30)
        const cheatCount = ref(3)

        // 游戏元素
        const moths = ref<MOTH[]>([])
        const effects = ref<EFFECT[]>([])

        // 游戏配置
        const gameDuration = 30 // 游戏时长（秒）
        const maxMoths = 8 // 最多同时出现的飞蛾数量
        const mothSpawnInterval = 800 // 生成飞蛾的间隔（毫秒）

        let gameInterval: number | null = null
        let spawnInterval: number | null = null
        let idCounter = 0

        // 计算属性
        const gameAreaWidth = computed(() => {
            return window.innerWidth * 0.8
        })

        const gameAreaHeight = computed(() => {
            return window.innerHeight * 0.6
        })

        // 生成随机数
        const getRandomInt = (min: number, max: number): number => {
            return Math.floor(Math.random() * (max - min + 1)) + min
        }

        // 生成飞蛾
        const spawnMoth = (): void => {
            if (moths.value.length >= maxMoths) return

            const isCheatMoth = Math.random() < 0.2 // 20% 概率生成作弊飞蛾
            const size = getRandomSize()
            const scale = size === 'large' ? 1.2 : size === 'medium' ? 1.0 : 0.8

            const newMoth: MOTH = {
                id: idCounter++,
                x: getRandomInt(20, gameAreaWidth.value - 80),
                y: getRandomInt(20, gameAreaHeight.value - 80),
                size,
                scale,
                isCheat: isCheatMoth,
                clicked: false
            }

            moths.value.push(newMoth)

            // 5秒后移除未点击的飞蛾
            setTimeout(() => {
                const index = moths.value.findIndex(m => m.id === newMoth.id)
                if (index !== -1 && !newMoth.clicked) {
                    moths.value.splice(index, 1)
                }
            }, 5000)
        }

        // 获取随机大小
        const getRandomSize = (): 'small' | 'medium' | 'large' => {
            const rand = Math.random()
            if (rand < 0.3) return 'small'
            if (rand < 0.7) return 'medium'
            return 'large'
        }

        // 处理飞蛾点击
        const handleMothClick = (moth: MOTH): void => {
            if (gameState.value !== 'playing' || moth.clicked) return

            moth.clicked = true

            // 根据飞蛾类型计算得分
            let points = 0
            if (moth.isCheat) {
                points = 10
                cheatCount.value += 1
                createEffect(moth.x, moth.y, points, 'cheat')
            } else {
                points = moth.size === 'large' ? 1 : moth.size === 'medium' ? 3 : 5
                createEffect(moth.x, moth.y, points, 'positive')
            }

            score.value += points

            // 移除被点击的飞蛾
            setTimeout(() => {
                const index = moths.value.findIndex(m => m.id === moth.id)
                if (index !== -1) {
                    moths.value.splice(index, 1)
                }
            }, 300)
        }

        // 创建效果
        const createEffect = (x: number, y: number, value: number, type: 'positive' | 'negative' | 'cheat'): void => {
            const effect: EFFECT = {
                id: idCounter++,
                x: x + 20,
                y: y - 10,
                value,
                type,
                createdAt: Date.now()
            }

            effects.value.push(effect)

            // 1.5秒后移除效果
            setTimeout(() => {
                const index = effects.value.findIndex(e => e.id === effect.id)
                if (index !== -1) {
                    effects.value.splice(index, 1)
                }
            }, 1500)
        }

        // 处理背景点击（误点击）
        const handleBackgroundClick = (): void => {
            if (gameState.value !== 'playing') return

            // 减少分数（惩罚）
            if (score.value > 0) {
                score.value -= 1
                createEffect(
                    getRandomInt(50, gameAreaWidth.value - 50),
                    getRandomInt(50, gameAreaHeight.value - 50),
                    -1,
                    'negative'
                )
            }
        }

        // 使用作弊
        const useCheat = (): void => {
            if (gameState.value !== 'playing' || cheatCount.value <= 0) return

            cheatCount.value--

            // 为所有可见的飞蛾增加分数
            moths.value.forEach(moth => {
                if (!moth.clicked) {
                    const points = moth.isCheat ? 10 : moth.size === 'large' ? 1 : moth.size === 'medium' ? 3 : 5
                    score.value += points
                    createEffect(moth.x + 20, moth.y - 10, points, 'positive')

                    // 标记为已点击并移除
                    moth.clicked = true
                    setTimeout(() => {
                        const index = moths.value.findIndex(m => m.id === moth.id)
                        if (index !== -1) {
                            moths.value.splice(index, 1)
                        }
                    }, 300)
                }
            })
        }

        // 开始游戏
        const startGame = (): void => {
            resetGame()
            gameState.value = 'playing'
            score.value = 0
            timeLeft.value = gameDuration
            cheatCount.value = 3

            // 设置游戏计时器
            gameInterval = window.setInterval(() => {
                timeLeft.value--
                if (timeLeft.value <= 0) {
                    endGame()
                }
            }, 1000)

            // 设置飞蛾生成计时器
            spawnInterval = window.setInterval(spawnMoth, mothSpawnInterval)

            // 立即生成一些飞蛾
            for (let i = 0; i < 3; i++) {
                spawnMoth()
            }
        }

        // 结束游戏
        const endGame = (): void => {
            if (gameInterval !== null) {
                clearInterval(gameInterval)
                gameInterval = null
            }

            if (spawnInterval !== null) {
                clearInterval(spawnInterval)
                spawnInterval = null
            }

            gameState.value = 'gameOver'
            moths.value = []
            effects.value = []
        }

        // 重置游戏
        const resetGame = (): void => {
            if (gameInterval !== null) {
                clearInterval(gameInterval)
                gameInterval = null
            }

            if (spawnInterval !== null) {
                clearInterval(spawnInterval)
                spawnInterval = null
            }

            gameState.value = 'idle'
            moths.value = []
            effects.value = []
        }

        // 组件卸载时清理
        onUnmounted(() => {
            if (gameInterval !== null) {
                clearInterval(gameInterval)
            }

            if (spawnInterval !== null) {
                clearInterval(spawnInterval)
            }
        })

        return {
            gameState,
            score,
            timeLeft,
            cheatCount,
            moths,
            effects,
            startGame,
            useCheat,
            resetGame,
            handleMothClick,
            handleBackgroundClick
        }
    }
})
</script>

<style lang="scss" scoped>
$primary-color: #4a90e2;
$secondary-color: #50c878;
$danger-color: #e74c3c;
$warning-color: #f39c12;
$background-color: #f8f9fa;
$text-color: #333;
$light-text: #fff;

.moth-game-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Arial', sans-serif;
    color: $text-color;

    .game-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding: 15px;
        background-color: $primary-color;
        color: $light-text;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

        h1 {
            margin: 0;
            font-size: 28px;
        }

        .score-container,
        .time-container {
            display: flex;
            flex-direction: column;
            align-items: center;

            .score-label,
            .time-label {
                font-size: 14px;
                opacity: 0.9;
            }

            .score,
            .time {
                font-size: 24px;
                font-weight: bold;
            }
        }
    }

    .game-area {
        position: relative;
        width: 100%;
        height: 60vh;
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        border-radius: 15px;
        overflow: hidden;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
        cursor: pointer;

        .moth {
            position: absolute;
            width: 40px;
            height: 30px;
            transition: transform 0.2s ease, opacity 0.3s ease;
            cursor: pointer;
            z-index: 10;

            &.moth-clicked {
                opacity: 0;
                transform: scale(1.5) !important;
            }

            // 飞蛾大小
            &.moth-small {
                transform: scale(0.8);
            }

            &.moth-medium {
                transform: scale(1.0);
            }

            &.moth-large {
                transform: scale(1.2);
            }

            // 作弊飞蛾样式
            &.moth-cheat {
                animation: pulse 1s infinite;

                .moth-wing {
                    background-color: $warning-color;
                }

                .moth-body {
                    background-color: darken($warning-color, 20%);
                }
            }

            // 飞蛾翅膀
            .moth-wing {
                position: absolute;
                width: 25px;
                height: 30px;
                background-color: #8b4513;
                border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;

                &.left {
                    left: 0;
                    transform: rotate(-30deg);
                }

                &.right {
                    right: 0;
                    transform: rotate(30deg);
                }
            }

            // 飞蛾身体
            .moth-body {
                position: absolute;
                left: 17px;
                top: 8px;
                width: 6px;
                height: 14px;
                background-color: #5d4037;
                border-radius: 50%;
            }

            // 飞蛾眼睛
            .moth-eye {
                position: absolute;
                width: 4px;
                height: 4px;
                background-color: #000;
                border-radius: 50%;
                top: 5px;

                &.left {
                    left: 15px;
                }

                &.right {
                    right: 15px;
                }
            }
        }

        .effect {
            position: absolute;
            font-weight: bold;
            pointer-events: none;
            animation: float-up 1.5s forwards;

            &.positive {
                color: $secondary-color;
            }

            &.negative {
                color: $danger-color;
            }

            &.cheat {
                color: $warning-color;
                font-weight: bold;
                text-shadow: 0 0 5px rgba($warning-color, 0.7);
            }
        }
    }

    .game-controls {
        display: flex;
        justify-content: center;
        gap: 15px;
        margin-top: 20px;

        button {
            padding: 12px 24px;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
            }

            &:active {
                transform: translateY(0);
            }
        }

        .start-button {
            background-color: $primary-color;
            color: $light-text;
        }

        .cheat-button {
            background-color: $warning-color;
            color: $light-text;

            &:disabled {
                background-color: #ccc;
                cursor: not-allowed;
                transform: none;
            }
        }

        .reset-button {
            background-color: #95a5a6;
            color: $light-text;
        }
    }

    .game-over-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 100;

        .game-over-content {
            background-color: $light-text;
            padding: 30px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);

            h2 {
                margin-top: 0;
                color: $primary-color;
            }

            p {
                font-size: 18px;
                margin-bottom: 20px;
            }

            .restart-button {
                padding: 10px 20px;
                background-color: $secondary-color;
                color: $light-text;
                border: none;
                border-radius: 25px;
                font-size: 16px;
                cursor: pointer;
                transition: all 0.3s ease;

                &:hover {
                    background-color: darken($secondary-color, 10%);
                }
            }
        }
    }
}

// 动画
@keyframes float-up {
    0% {
        opacity: 1;
        transform: translateY(0);
    }

    100% {
        opacity: 0;
        transform: translateY(-50px);
    }
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba($warning-color, 0.7);
    }

    70% {
        box-shadow: 0 0 0 10px rgba($warning-color, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba($warning-color, 0);
    }
}

// 响应式设计
@media (max-width: 768px) {
    .moth-game-container {
        padding: 10px;

        .game-header {
            flex-direction: column;
            gap: 10px;

            h1 {
                font-size: 24px;
            }

            .score-container,
            .time-container {
                flex-direction: row;
                gap: 10px;

                .score-label,
                .time-label {
                    font-size: 16px;
                }

                .score,
                .time {
                    font-size: 20px;
                }
            }
        }

        .game-controls {
            flex-direction: column;
            align-items: center;

            button {
                width: 80%;
                max-width: 300px;
            }
        }
    }
}
</style>